package com.Server.Client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.logging.Logger;

import com.Server.StreamUtil;
import com.Server.DataBase.BanIpTable;
import com.Server.DataBase.UuidTable;

public class SendMag implements Runnable {

	private static Logger _log = Logger.getLogger(SendMag.class.getName());
	
	
	private Socket _socket;
	private OutputStream _out;
	private InputStream _in;
	private String _ip, _uuid , _msg;

	public SendMag(Socket so , final String msg , final String ip) throws IOException{
		_socket = so;
		_out = _socket.getOutputStream();
		_msg = msg;
		_in = _socket.getInputStream();
		_ip = ip;
	}



	@Override
	public void run() {
		BufferedWriter out =  new BufferedWriter(new OutputStreamWriter(_out));
		try {
			out.write("ok");
			out.newLine();
			out.flush();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		BufferedReader br = new BufferedReader(new InputStreamReader(_in));
		try{
			while((_uuid = br.readLine()) != null){
					UuidTable.getInstance().insertUUIDLog(_ip, _uuid);
				break;
				}
		}catch(Exception e){
		}
		final boolean badUuid = UuidTable.getInstance().chaekUUID(_uuid);
		
		if(_uuid !=null && badUuid){
			_msg = "bye";
			BanIpTable.getInstance().banIp(_ip, _ip);
		}
		if(!_msg.equals("ok")){
			_log.info("禁止連線的IP: "+_ip+" 回傳 "+_msg);
			if(!badUuid){
				UuidTable.getInstance().badUUID(_uuid);
			}
			Process p;
			try {
				p = Runtime.getRuntime().exec("./sound.bat");
				p.waitFor();
				p.destroy(); //破壞物件
			} catch (IOException | InterruptedException e) {
				e.printStackTrace();
			} //執行DOS指令settime.bat
		}else{
			_log.info("嘗試連線的IP	: "+_ip);
		}
		try {
			out.write(_msg);
			out.newLine();
			out.flush();
			while(_in.read() ==-1){
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			StreamUtil.close(_out, _in , out);
			StreamUtil.close(_socket);
			_socket = null;
		}
	}


}
